package com.link.base.base.accnt.service;

import com.link.base.base.accnt.model.*;
import com.link.base.base.accnt.model.*;
import com.link.base.base.contacts.model.Contacts;
import com.link.base.base.contacts.service.ContactsService;
import com.link.base.base.fund.model.DealerAccount;
import com.link.base.base.fund.service.DealerAccountService;
import com.link.base.base.mvg.dao.mybatis.accnt.mapper.*;
import com.link.base.base.mvg.model.Mvg;
import com.link.base.base.orgnization.model.Orgnization;
import com.link.base.base.orgnization.service.OrgnizationService;
import com.link.base.base.position.model.Position;
import com.link.base.base.position.service.PositionService;
import com.link.base.base.product.dao.mybatis.mapper.PriceListMapper;
import com.link.base.base.product.model.PriceList;
import com.link.base.core.apiutils.ApiBeanUtils;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.StringUtils;
import com.link.base.base.mvg.dao.mybatis.accnt.mapper.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Copyright  hande Company. All Rights Reserved.
 *
 * @author unknwon
 * @version 1.0
 * @date: 2018/11/12 16:10
 */

@Service
public class ApiAccntServiceImpl implements ApiAccntService {
    @Resource
    private KeyGenerateService keyGenerateService;
    @Resource
    private AccountService accountService;
    @Resource
    private AcctAddressService acctAddressService;
    @Resource
    private ContactsService contactsService;
    @Resource
    private OrgnizationService orgnizationService;
    @Resource
    private SaleRegionService saleRegionService;
    //@Resource
    //private QidianBrandService qidianBrandService;
    @Resource
    private AccntSaleregMvgMapper accntSaleregMvgMapper;

    @Resource
    private AccntPriceListMvgMapper accntPriceListMvgMapper;

    @Resource
    private PriceListMapper priceListMapper;

    @Resource
    private PositionService positionService;

    @Resource
    private AccntPostnMvgMapper accntPostnMvgMapper;


    @Resource
    private ContactOrgMvgMapper contactOrgMvgMapper;

    @Resource
    private AccntOrgMvgMapper accntOrgMvgMapper;

    @Resource
    private DealerAccountService dealerAccountService;

    /**
     * 获取Service
     */
    public BasicService<Account> getBasicService() throws Exception {
        return accountService;
    }

    /**
     * 根据id查询价格表与价格表行数据l
     *
     * @param crmId
     * @return ApiAccount
     * @throws Exception
     */
    @Override
    public ApiAccount getHeadAndItem(Long crmId) throws Exception {
        Long acctId = crmId;
        if (null == acctId) {
            throw new ServiceException("PUBLIC-007");
        }
        ApiAccount accountExt = null;
        Account example = new Account();
        example.setId(acctId);
        Account account = accountService.queryById(example);
        if (account != null) {
            accountExt = new ApiAccount();
            // 大量数据时不宜采用,应直接结果集映射到目标对象
            BeanUtils.copyProperties(account, accountExt);

            List<AcctAddress> addrList = queryAddressListByAcctId(acctId);
            accountExt.setAcctAddressList(addrList);

            List<Contacts> contactsList = queryContactsListByAcctId(acctId);
            accountExt.setAcctContactList(contactsList);

            List<QidianBrand> brandList = queryBrandListByAcctId(acctId);
            accountExt.setBrandList(brandList);

            List<SaleRegion> saleRegionList = querySaleRegionListByAcctId(acctId);
            accountExt.setSaleRegionList(saleRegionList);

            List<PriceList> priceList = queryPriceListListByAcctId(acctId);
            accountExt.setPriceList(priceList);

            List<Position> positionList = queryPositionByAccntId(acctId);
            accountExt.setPostnList(positionList);

            List<Orgnization> orgList = getAccountOrg(acctId);
            accountExt.setOrgList(orgList);

            List<DealerAccount> dealerAccountList = getDealerAccount(acctId);
            accountExt.setDealerAccountList(dealerAccountList);
        }
        return accountExt;
    }

    /**
     * 更新头行
     */
    @Transactional(rollbackFor = ServiceException.class)
    @Override
    public ApiAccount upsertHeadAndItem(ApiAccount model) throws Exception {
        checkOrg(model.getOrgId());
        Account account = check(model);
        // 地址
        List<AcctAddress> apiAcctAddressList = model.getAcctAddressList();
        // 联系人
        List<Contacts> acctContactList = model.getAcctContactList();
        // 销售品牌
        List<QidianBrand> brandList = model.getBrandList();
        // 销售区域
        List<SaleRegion> saleRegionList = model.getSaleRegionList();
        //品类
        List<PriceList> priceList = model.getPriceList();
        //职位列表
        List<Position> positionList = model.getPostnList();
        //组织列表
        List<Orgnization> orgList = model.getOrgList();
        List<DealerAccount> dealerAccountList = model.getDealerAccountList();
        // 新增客户
        if (account == null) {
            account = new Account();
            Long id = keyGenerateService.keyGenerate();
            ApiBeanUtils.copyProperties(model, account);
            account.setId(id);
            account.setNoJoinFlag(model.getNoJoinFlag());

            //设置主要价格表id
            if (priceList != null && priceList.size() > 0) {
                Long primaryPriceListId = getPrimaryPriceList(priceList);
                account.setPriceListId(primaryPriceListId);
            }

            //设置主要职位id
            if (positionList != null && positionList.size() > 0) {
                Long primaryPositionId = getPrimaryPosition(positionList);
                account.setPostnId(primaryPositionId);
            }

            //设置主要销售区域Id
            if (orgList != null && orgList.size() > 0) {
                Long primaryOrgId = getPrimaryOrgId(orgList);
                account.setOrgId(primaryOrgId);
            }

            //设置主要销售区域id
            if (saleRegionList != null && saleRegionList.size() > 0) {
                Long primarySaleRegionId = getPrimaryRegionId(saleRegionList);
                account.setxAttr58(String.valueOf(primarySaleRegionId));
            }

            accountService.insert(account);
            if (acctContactList != null && acctContactList.size() > 0) {
                setContacts(id, acctContactList, true);
            }
            if (apiAcctAddressList != null && apiAcctAddressList.size() > 0) {
                setAccountAddress(id, apiAcctAddressList, acctContactList, true);
            }
            if (brandList != null && brandList.size() > 0) {
                setBrand(id, brandList, true);
            }
            if (saleRegionList != null && saleRegionList.size() > 0) {
                setSaleRegion(id, saleRegionList, true);
            }

            //设置价格表
            if (priceList != null && priceList.size() > 0) {
                setPriceList(id, priceList, false);
            }

            //设置职位
            if (positionList != null && positionList.size() > 0) {
                setPosition(id, positionList, false);
            }

            //设置组织
            if (orgList != null && orgList.size() > 0) {
                setAccountOrg(id, orgList, false);
            }

            //设置经销商资金账户
            if (dealerAccountList != null && dealerAccountList.size() > 0) {
                setDealerAccount(id, dealerAccountList);
            }
        } else { // 更新客户
            Long id = account.getId();
            ApiBeanUtils.copyProperties(model, account);
            account.setId(id);
            account.setNoJoinFlag(model.getNoJoinFlag());

            //设置主要价格表id
            if (priceList != null && priceList.size() > 0) {
                Long primaryPriceListId = getPrimaryPriceList(priceList);
                account.setPriceListId(primaryPriceListId);
            }

            //设置主要职位id
            if (positionList != null && positionList.size() > 0) {
                Long primaryPositionId = getPrimaryPosition(positionList);
                account.setPostnId(primaryPositionId);
            }

            //设置主要组织Id
            if (orgList != null && orgList.size() > 0) {
                Long primaryOrgId = getPrimaryOrgId(orgList);
                account.setOrgId(primaryOrgId);
            }

            //设置主要销售区域id
            if (saleRegionList != null && saleRegionList.size() > 0) {
                Long primarySaleRegionId = getPrimaryRegionId(saleRegionList);
                account.setxAttr58(String.valueOf(primarySaleRegionId));
            }

            accountService.update(account);
            if (acctContactList != null && acctContactList.size() > 0) {
                setContacts(account.getId(), acctContactList, false);
            }
            if (apiAcctAddressList != null && apiAcctAddressList.size() > 0) {
                setAccountAddress(account.getId(), apiAcctAddressList, acctContactList, false);
            }
//          if (brandList!= null && brandList.size()>0) {
            if (brandList != null) {
                setBrand(id, brandList, false);
            }
            if (saleRegionList != null && saleRegionList.size() > 0) {
                setSaleRegion(id, saleRegionList, false);
            }

            //设置价格表
            if (priceList != null && priceList.size() > 0) {
                setPriceList(account.getId(), priceList, false);
            }

            //设置职位
            if (positionList != null && positionList.size() > 0) {
                setPosition(account.getId(), positionList, false);
            }

            //设置组织
            if (orgList != null && orgList.size() > 0) {
                setAccountOrg(account.getId(), orgList, false);
            }

            //设置经销商资金账户
            if (dealerAccountList != null && dealerAccountList.size() > 0) {
                setDealerAccount(account.getId(), dealerAccountList);
            }
        }
        ApiAccount accountExt = getHeadAndItem(account.getId());
        return accountExt;
    }

    /**
     * 查询指定客户的地址
     *
     * @param acctId 客户ID
     */
    private List<AcctAddress> queryAddressListByAcctId(Long acctId) throws Exception {
        AcctAddress example = new AcctAddress();
        example.setAcctId(acctId);
        example.setPageFlag(false);
        List<AcctAddress> list = acctAddressService.queryByExamplePage(example);
        return list;
    }

    /**
     * 查询指定客户的联系人
     *
     * @param acctId 客户ID
     */
    private List<Contacts> queryContactsListByAcctId(Long acctId) throws Exception {
        Contacts example = new Contacts();
        example.setAcctId(acctId);
        example.setPageFlag(false);
        List<Contacts> list = contactsService.queryByExamplePage(example);
        // 获取Contacts 的组织
        List<Contacts> retList = new ArrayList<Contacts>();
        for (Contacts cot : list) {
            Long contactId = cot.getId();
            List<Orgnization> orgList = getContactOrg(contactId);
            if (orgList != null && orgList.size() > 0) {
                cot.setOrgList(orgList);
                retList.add(cot);
            } else {
                retList.add(cot);
            }
        }
        return retList;
    }

    /**
     * 查询指定客户的销售品牌
     *
     * @param acctId 客户ID
     */
    private List<QidianBrand> queryBrandListByAcctId(Long acctId) throws Exception {
        QidianBrand example = new QidianBrand();
        example.setHeadId(acctId);
        example.setPageFlag(false);
        List<QidianBrand> list = null;// qidianBrandService.queryByExamplePage(example);
        return list;
    }

    /**
     * 查询指定客户的销售区域
     *
     * @param acctId 客户ID
     */
    private List<SaleRegion> querySaleRegionListByAcctId(Long acctId) throws Exception {
        SaleRegion example = new SaleRegion();
        example.setAcctId(acctId);
        example.setPageFlag(false);
        return saleRegionService.queryByAcctIdPage(example);
    }

    /**
     * <p>
     * 检查该记录是否已存在，是则返回对象，否则返回null
     * </p>
     * @author wx
     * @param model
     * @return Account
     * @throws Exception
     *
     */
    private Account check(ApiAccount model) throws Exception {
        Long id = model.getCrmId();
        String integrationId = model.getIntegrationId();
        if (StringUtils.isBlank(integrationId)) {
            throw new ServiceException("集成" + "PUBLIC-007");
        }
        Account account = null;
        // 通过集成ID校验记录
        if (null == id) {
            Account example = new Account();
            example.setIntegrationId(integrationId);
            example.setPageFlag(false);
            List<Account> list = accountService.queryByExamplePage(example);
            if (list != null && list.size() > 0) {
                if (list.size() == 1) {
                    account = list.get(0);
                } else {
                    throw new ServiceException("ACCT-016");
                }
            }
        } else { // 通过linkcrm客户ID校验记录
            Account example = new Account();
            example.setId(id);
            account = accountService.queryById(example);
            if (account == null) {
                throw new ServiceException("ACCT-017",id.toString());
            } else if (!"".equals(account.getIntegrationId()) && account.getIntegrationId() != null
                    && !integrationId.equals(account.getIntegrationId())) {
                throw new ServiceException("ACCT-018");
            }
        }
        return account;
    }

    /**
     * <p>
     * 根据api客户地址获取linkcrm客户地址
     * </p>
     * @author wx
     * @param accntAddrModel
     * @return AcctAddress
     * @throws Exception
     *
     */
    private AcctAddress getAcctAddress(Long accntId, AcctAddress accntAddrModel) throws Exception {
        AcctAddress acctAddress = null;
        // linkcrm客户地址id
        Long crmId = accntAddrModel.getCrmId();
        // siebel客户地址id
        String integrationId = accntAddrModel.getIntegrationId();
        if (StringUtils.isBlank(integrationId)) {
            throw new ServiceException("客户地址集成" + "PUBLIC-007");
        }

        if (null != crmId) {
            AcctAddress param = new AcctAddress();
            param.setId(crmId);
            acctAddress = acctAddressService.queryById(param);
            if (acctAddress == null) {
                throw new ServiceException("ACCT-019",crmId.toString());
            }
            if (StringUtils.isNotBlank(acctAddress.getIntegrationId())
                    && !StringUtils.equals(integrationId, acctAddress.getIntegrationId())) {
                throw new ServiceException("ACCT-020",integrationId);
            }
            return acctAddress;
        }

        AcctAddress example = new AcctAddress();
        example.setIntegrationId(integrationId);
        example.setPageFlag(false);
        example.setAcctId(accntId);
        List<AcctAddress> list = acctAddressService.queryByExamplePage(example);
        if (list != null && list.size() > 0) {
            if (list.size() == 1) {
                acctAddress = list.get(0);
            } else {
                throw new ServiceException("ACCT-016");
            }
        }
        return acctAddress;
    }

    /**
     * <p>
     * 根据api客户联系人获取linkcrm客户联系人
     * </p>
     * @author wx
     * @param model
     * @return Contacts
     * @throws Exception
     *
     */
    private Contacts getAcctContacts(Long accntId, Contacts model) throws Exception {
        Contacts contacts = null;
        // linkcrm客户联系人id
        Long crmId = model.getCrmId();
        // siebel客户联系人id
        String integrationId = model.getIntegrationId();
        if (StringUtils.isBlank(integrationId)) {
            throw new ServiceException("客户联系人集成" + "PUBLIC-007");
        }

        if (null != crmId) {
            Contacts param = new Contacts();
            param.setId(crmId);
            contacts = contactsService.queryById(param);
            if (contacts == null) {
                throw new ServiceException("ACCT-021",crmId.toString());
            }
            if (StringUtils.isNotBlank(contacts.getIntegrationId())
                    && !StringUtils.equals(integrationId, contacts.getIntegrationId())) {
                throw new ServiceException("ACCT-020",integrationId);
            }
            return contacts;
        }

        Contacts example = new Contacts();
        example.setIntegrationId(integrationId);
        example.setAcctId(accntId);
        example.setPageFlag(false);
        List<Contacts> list = contactsService.queryByExamplePage(example);
        if (list != null && list.size() > 0) {
            if (list.size() == 1) {
                contacts = list.get(0);
            } else {
                throw new ServiceException("ACCT-016");
            }
        }

        return contacts;
    }

    /**
     * <p>
     * 根据api客户销售品牌获取linkcrm客户销售品牌
     * </p>
     * @author wx
     * @param accntId
     * @param model
     * @return QidianBrand
     * @throws Exception
     *
     */
    private QidianBrand getBrand(Long accntId, QidianBrand model) throws Exception {
        QidianBrand contacts = null;
        // linkcrm客户联系人id
        Long crmId = model.getCrmId();
        // siebel客户联系人id
        String integrationId = model.getIntegrationId();
        if (StringUtils.isBlank(integrationId)) {
            throw new ServiceException("销售品牌集成" + "PUBLIC-007");
        }

        if (null != crmId) {
            QidianBrand param = new QidianBrand();
            param.setId(crmId);
            // contacts = qidianBrandService.queryById(param);
            if (contacts == null) {
                throw new ServiceException("ACCT-022",crmId.toString());
            }
            if (StringUtils.isNotBlank(contacts.getIntegrationId())
                    && !StringUtils.equals(integrationId, contacts.getIntegrationId())) {
                throw new ServiceException("ACCT-023",integrationId);
            }
            return contacts;
        }

//        QidianBrand example = new QidianBrand();
//        example.setIntegrationId(integrationId);
//        example.setHeadId(accntId);
//        example.setPageFlag(false);
//        List<QidianBrand> list = null;//qidianBrandService.queryByExamplePage(example);
//        if (list != null && list.size() > 0) {
//            if (list.size() == 1) {
//                contacts = list.get(0);
//            } else {
//                throw new ServiceException("ACCT-024",integrationId);
//            }
//        }

        return contacts;
    }

    /**
     * <p>
     * 写入客户的地址信息列表
     * </p>
     * @author wx
     * @param accntId linkcrm客户ID
     * @param list    linkcrm的客户地址list
     * @param isNew   是否新建客户
     * @throws Exception
     *
     */
    private void setAccountAddress(Long accntId, List<AcctAddress> list, List<Contacts> acctContactList,
                                   boolean isNew) throws Exception {
        List<AcctAddress> currentAddressList = queryAddressListByAcctId(accntId);
        // 删除当前系统里面有，但是没有传过来的
        Iterator<AcctAddress> it = currentAddressList.iterator();
        while (it.hasNext()) {
            AcctAddress origItem = it.next();
            boolean existFlag = false;
            for (AcctAddress remoteItem : list) {
                if (origItem.getIntegrationId() != null && !"".equals(origItem.getIntegrationId())
                        && StringUtils.equals(origItem.getIntegrationId(), remoteItem.getIntegrationId())) {
                    existFlag = true;
                    break;
                }
            }
            if (!existFlag && origItem.getIntegrationId() != null && !"".equals(origItem.getIntegrationId())) {
                // 删除多余的
                acctAddressService.deleteById(origItem);
                it.remove();
            }
        }

        // 把当前的插入或者更新到数据库
        // 主要客户地址ID
        Long acctAddressId = null;
        for (AcctAddress apiAccntAddr : list) {
            if (StringUtils.isBlank(apiAccntAddr.getIntegrationId())) {
                throw new ServiceException("ACCT-025");
            }
            Long contactId = null;
            if (apiAccntAddr.getContactIntId() != null) {
                // 校验地址的联系人是否存在
                Contacts contacts = new Contacts();
                contacts.setTotalFlag(true);
                contacts.setPageFlag(false);
                contacts.setIntegrationId(String.valueOf(apiAccntAddr.getContactIntId()));
                List<Contacts> listCont = contactsService.queryByExamplePage(contacts);
                if (listCont.size() < 1) {
                    throw new ServiceException("ACCT-026",apiAccntAddr.getContactIntId().toString());
                }
                if (listCont.size() > 1) {
                    throw new ServiceException("ACCT-027",apiAccntAddr.getContactIntId().toString());
                }
                contactId = listCont.get(0).getId();
            }
            AcctAddress acctAddress = null;
            if (!isNew) {
                acctAddress = getAcctAddress(accntId, apiAccntAddr);
            }
            // 新增客户地址记录
            if (acctAddress == null) {
                Long id = keyGenerateService.keyGenerate();
                // 客户地址记录id
                apiAccntAddr.setId(id);
                // 客户ID
                apiAccntAddr.setAcctId(accntId);
                apiAccntAddr.setContactId(contactId);
                acctAddressService.insert(apiAccntAddr);
            } else {
                // 更新客户地址记录
                // 客户地址记录id
                apiAccntAddr.setId(acctAddress.getId());
                // 客户ID
                apiAccntAddr.setAcctId(accntId);
                apiAccntAddr.setContactId(contactId);
                acctAddressService.update(apiAccntAddr);
            }

            if (StringUtils.equals(apiAccntAddr.getIsDefault(), "Y")) {
                // 记录主要地址id
                acctAddressId = apiAccntAddr.getId();
            }
        }
        if (null != acctAddressId) {
            // 更新主要地址
            AcctAddress addrParam = new AcctAddress();
            addrParam.setId(acctAddressId);
            addrParam.setAcctId(accntId);
            acctAddressService.defaultAddrUpdate(addrParam);
        }
    }

    /**
     * <p>
     * 写入客户的联系人信息列表
     * </p>
     * @author wx
     * @param accntId linkcrm客户ID
     * @param list    linkcrm的客户联系人list
     * @param isNew   是否新建客户
     * @throws Exception
     *
     */
    private void setContacts(Long accntId, List<Contacts> list, boolean isNew) throws Exception {
        List<Contacts> currentContactsList = queryContactsListByAcctId(accntId);
        // 删除当前系统里面有，但是没有传过来的
        Iterator<Contacts> it = currentContactsList.iterator();
        while (it.hasNext()) {
            Contacts origItem = it.next();
            boolean existFlag = false;
            for (Contacts remoteItem : list) {
                if (origItem.getIntegrationId() != null && !"".equals(origItem.getIntegrationId())
                        && StringUtils.equals(origItem.getIntegrationId(), remoteItem.getIntegrationId())) {
                    existFlag = true;
                    break;
                }
            }
            if (!existFlag && origItem.getIntegrationId() != null && !"".equals(origItem.getIntegrationId())) {
                // 删除多余的
                contactsService.deleteById(origItem);
                it.remove();
            }
        }
        // 主要联系人ID
        Long mainContactId = null;
        for (Contacts apiContacts : list) {
            checkOrg(apiContacts.getOrgId());
            if (StringUtils.isBlank(apiContacts.getIntegrationId())) {
                throw new ServiceException("联系人集成" + "PUBLIC-007");
            }
            Contacts contacts = null;
            if (!isNew) {
                contacts = getAcctContacts(accntId, apiContacts);
            }
            // 新增客户联系人记录
            if (contacts == null) {
                contacts = new Contacts();
                Long id = keyGenerateService.keyGenerate();
                // 客户联系人记录id
                apiContacts.setId(id);
                // 客户ID
                apiContacts.setAcctId(accntId);

                //设置主要组织id
                List<Orgnization> orgList = apiContacts.getOrgList();
                Long primaryOrgId = getPrimaryOrgId(orgList);
                apiContacts.setOrgId(primaryOrgId);

                contactsService.insert(apiContacts);
            } else {
                // 更新
                apiContacts.setId(contacts.getId());
                // 客户ID
                apiContacts.setAcctId(contacts.getAcctId());

                //设置主要组织id
                List<Orgnization> orgList = apiContacts.getOrgList();
                Long primaryOrgId = getPrimaryOrgId(orgList);
                apiContacts.setOrgId(primaryOrgId);

                contactsService.update(apiContacts);
            }

            //设置联系人组织
            //设置主要组织id
            List<Orgnization> orgList = apiContacts.getOrgList();
            if (orgList != null) {
                setContactsOrg(apiContacts.getId(), orgList, false);
            }

            if (StringUtils.equals(apiContacts.getIsAcctDefault(), "Y")) {
                mainContactId = apiContacts.getId();
            }
        }
        if (null != mainContactId) {
            // 更新主要联系人
            Account acctParam = new Account();
            acctParam.setId(accntId);
            acctParam.setContactId(mainContactId);
            accountService.mainContactUpdate(acctParam);
        }
    }

    /**
     * <p>
     * 写入客户的销售品牌列表
     * </p>
     * @author heqq
     * @param accntId linkcrm客户ID
     * @param list    linkcrm的客户联系人list
     * @param isNew   是否新建客户
     * @throws Exception
     *
     */
    private void setBrand(Long accntId, List<QidianBrand> list, boolean isNew) throws Exception {
        // 两边数据对比，将没匹配上的数据删除
//        List<QidianBrand> origList = queryBrandListByAcctId(accntId);
//        Iterator<QidianBrand> it = origList.iterator();
//        while (it.hasNext()) {
//            QidianBrand origItem = it.next();
//            boolean existFlag = false;
//            for (QidianBrand remoteItem : list) {
//                if (null != origItem.getCrmId() && origItem.getCrmId().equals(remoteItem.getCrmId())
//                        || StringUtils.equals(origItem.getIntegrationId(), remoteItem.getIntegrationId())) {
//                    existFlag = true;
//                    break;
//                }
//            }
//            if (!existFlag) {
//                //qidianBrandService.deleteById(origItem);
//                it.remove();
//            }
//        }
//
//        for (QidianBrand item : list) {
//            if (StringUtils.isBlank(item.getIntegrationId())) {
//                throw new ServiceException("销售品牌集成" + "PUBLIC-007");
//            }
//            QidianBrand brand = null;
//            if (!isNew) {
//                brand = getBrand(accntId, item);
//            }
//            if (brand == null) {
//                // 新增
//                brand = new QidianBrand();
//                Long id = keyGenerateService.keyGenerate();
//                item.setId(id);
//                // 客户ID
//                item.setHeadId(accntId);
//                //qidianBrandService.insert(item);
//            } else {
//                // 更新
//                item.setId(brand.getId());
//                // 客户ID
//                item.setHeadId(brand.getHeadId());
//                //qidianBrandService.update(item);
//            }
//        }
    }

    /**
     * <p>
     * 写入客户的销售区域列表
     * </p>
     * @author heqq
     * @param accntId linkcrm客户ID
     * @param list    待处理的list
     * @param isNew   是否新建客户
     * @throws Exception
     *
     */
    private void setSaleRegion(Long accntId, List<SaleRegion> list, boolean isNew) throws Exception {
        // 两边数据对比，将没匹配上的数据删除
        List<SaleRegion> origList = querySaleRegionListByAcctId(accntId);
        Iterator<SaleRegion> it = origList.iterator();
        while (it.hasNext()) {
            SaleRegion origItem = it.next();
            boolean existFlag = false;
            for (SaleRegion remoteItem : list) {
                if (StringUtils.equals(origItem.getRegionCode(), remoteItem.getRegionCode())) {
                    existFlag = true;
                    break;
                }
            }
            if (!existFlag) {
                Mvg mvgParam = new Mvg();
                mvgParam.setMvgParentId(accntId);
                mvgParam.setMvgSubsetId(origItem.getId());
                accntSaleregMvgMapper.deleteById(mvgParam);
                it.remove();
            }
        }

        for (SaleRegion remoteItem : list) {
            boolean existFlag = false;
            for (SaleRegion origItem : origList) {
                if (StringUtils.equals(origItem.getRegionCode(), remoteItem.getRegionCode())) {
                    existFlag = true;
                    break;
                }
            }
            if (existFlag) {
                continue;
            }
            String regionCode = remoteItem.getRegionCode();
            SaleRegion sr = saleRegionService.queryByCode(regionCode);
            if (sr == null) {
                throw new ServiceException("ACCT-028",regionCode);
            }
            Mvg mvgParam = new Mvg();
            Long id = keyGenerateService.keyGenerate();
            mvgParam.setId(id);
            mvgParam.setMvgParentId(accntId);
            mvgParam.setMvgSubsetId(sr.getId());
            accntSaleregMvgMapper.insert(mvgParam);
        }
    }

    /**
     * @author huanglongjian
     * @param accntId
     * @param list
     * @param isNew
     * @throws Exception
     *
     * @ 设置价格表
     */
    private void setPriceList(Long accntId, List<PriceList> list, boolean isNew) throws Exception {
        // 两边数据对比，将没匹配上的数据删除
        List<PriceList> origList = queryPriceListListByAcctId(accntId);
        Iterator<PriceList> it = origList.iterator();
        while (it.hasNext()) {
            PriceList origItem = it.next();
            boolean existFlag = false;
//            for (PriceList remoteItem : list) {
//                if (StringUtils.equals(origItem.getPriceListName(), remoteItem.getPriceListName())) {
//                    if ("Y".equals(origItem.getAttr04())) {
//                        list.remove(remoteItem);
//                        continue;
//                    } else {
//                        existFlag = true;
//                        break;
//                    }
//                }
//            }
            //是否仅查看 为Y的时候，不做删除
//            if (!existFlag && !"Y".equals(origItem.getAttr04())) {
//                Mvg mvgParam = new Mvg();
//                mvgParam.setMvgParentId(accntId);
//                mvgParam.setMvgSubsetId(origItem.getId());
//                accntPriceListMvgMapper.deleteById(mvgParam);
//                it.remove();
//            }
        }

        for (PriceList remoteItem : list) {
            boolean existFlag = false;
            for (PriceList origItem : origList) {
                if (StringUtils.equals(origItem.getPriceListName(), remoteItem.getPriceListName())) {
                    existFlag = true;
                    break;
                }
            }
            if (existFlag) {
                continue;
            }
            Long crmId = remoteItem.getCrmId();
            PriceList priceList = new PriceList();
            priceList.setId(crmId);
            PriceList ol = priceListMapper.queryById(priceList);
            if (ol == null) {
                throw new ServiceException("ACCT-029",crmId.toString());
            }
            Mvg mvgParam = new Mvg();
            Long id = keyGenerateService.keyGenerate();
            mvgParam.setId(id);
            mvgParam.setMvgParentId(accntId);
            mvgParam.setMvgSubsetId(ol.getId());
            accntPriceListMvgMapper.insert(mvgParam);
        }
    }

    /**
     * 校验组织
     *
     * @param orgId 组织ID
     */
    private void checkOrg(Long orgId) throws Exception {
        if (null != orgId) {
            Orgnization orgParam = new Orgnization();
            orgParam.setId(orgId);
            Orgnization org = orgnizationService.queryById(orgParam);
            if (org == null) {
                throw new ServiceException("ACCT-030");
            }
        }
    }


    /**
     * @author huanglongjian
     * @param acctId
     * @return
     *
     * @查询MVG价格表
     */
    private List<PriceList> queryPriceListListByAcctId(Long acctId) throws Exception {
        PriceList queryPriceList = new PriceList();
        queryPriceList.setAccntId(acctId);
        List<PriceList> priceList = null;
        return accntPriceListMvgMapper.queryPriceListListByAcctIdForApi(queryPriceList);
    }

    /**
     * @author huanglongjian
     * @param priceList
     * @return Long
     * @throws Exception
     *
     * @ 获取价格表主要id
     */
    private Long getPrimaryPriceList(List<PriceList> priceList) throws Exception {
        Long crmId = null;
        for (PriceList list : priceList) {
            String flag = list.getIsAcctDefault();
            if ("Y".equals(flag)) {
                crmId = list.getCrmId();
                if (crmId == null) {
                    throw new ServiceException("ACCT-031");
                }
            }
        }
        if (crmId == null) {
            throw new ServiceException("ACCT-032");
        }
        return crmId;
    }

    /**
     * @author huanglongjian
     * @param position
     * @return Long
     * @throws Exception
     *
     * @ 获取价格表主要id
     */
    private Long getPrimaryPosition(List<Position> position) throws Exception {
        Long crmId = null;
        for (Position list : position) {
            String flag = list.getIsAcctDefault();
            if ("Y".equals(flag)) {
                crmId = list.getCrmId();
                if (crmId == null) {
                    throw new Exception("ACCT-033");
                }
            }
        }
        if (crmId == null) {
            throw new Exception("ACCT-034");
        }
        return crmId;
    }

    private List<Position> queryPositionByAccntId(Long accntId) throws Exception {
        Position positionQuery = new Position();
        positionQuery.setAcctId(accntId);
        return positionService.queryByAccntId(positionQuery);
    }

    /**
     * @author huanglongjian
     * @param accntId
     * @param list
     * @param isNew
     * @throws Exception
     *
     * @ 设置价格表
     */
    private void setPosition(Long accntId, List<Position> list, boolean isNew) throws Exception {
        // 两边数据对比，将没匹配上的数据删除
        List<Position> origList = queryPositionByAccntId(accntId);
        Iterator<Position> it = origList.iterator();
        while (it.hasNext()) {
            Position origItem = it.next();
            boolean existFlag = false;
            for (Position remoteItem : list) {
                if (null != origItem.getId() && origItem.getId().equals(remoteItem.getId())) {
                    existFlag = true;
                    break;
                }
            }
            if (!existFlag) {
                Mvg mvgParam = new Mvg();
                mvgParam.setMvgParentId(accntId);
                mvgParam.setMvgSubsetId(origItem.getId());
                accntPostnMvgMapper.deleteById(mvgParam);
                it.remove();
            }
        }

        for (Position remoteItem : list) {
            boolean existFlag = false;
            for (Position origItem : origList) {
                if (null != origItem.getId() && origItem.getId().equals(remoteItem.getId())) {
                    existFlag = true;
                    break;
                }
            }
            if (existFlag) {
                continue;
            }
            Long crmId = remoteItem.getCrmId();
            Position position = new Position();
            position.setId(crmId);
            Position ol = positionService.queryById(position);
            if (ol == null) {
                throw new ServiceException("ACCT-035",crmId.toString());
            }
            Mvg mvgParam = new Mvg();
            Long id = keyGenerateService.keyGenerate();
            mvgParam.setId(id);
            mvgParam.setMvgParentId(accntId);
            mvgParam.setMvgSubsetId(ol.getId());
            accntPostnMvgMapper.insert(mvgParam);
        }
    }

    /**
     * @author huanglongjian
     * @param contactId
     * @param list
     * @param isNew
     * @throws Exception
     *
     * @ 设置联系人的组织
     */
    private void setContactsOrg(Long contactId, List<Orgnization> list, boolean isNew) throws Exception {
        // 两边数据对比，将没匹配上的数据删除
        List<Orgnization> origList = getContactOrg(contactId);
        Iterator<Orgnization> it = origList.iterator();
        while (it.hasNext()) {
            Orgnization origItem = it.next();
            boolean existFlag = false;
            for (Orgnization remoteItem : list) {
                if (origItem.getId().equals(remoteItem.getCrmId())) {
                    existFlag = true;
                    break;
                }
            }
            if (!existFlag) {
                Mvg mvgParam = new Mvg();
                mvgParam.setMvgParentId(contactId);
                mvgParam.setMvgSubsetId(origItem.getId());
                contactOrgMvgMapper.deleteById(mvgParam);
                it.remove();
            }
        }

        for (Orgnization remoteItem : list) {
            boolean existFlag = false;
            for (Orgnization origItem : origList) {
                if (origItem.getId().equals(remoteItem.getCrmId())) {
                    existFlag = true;
                    break;
                }
            }
            if (existFlag) {
                continue;
            }
            Long crmId = remoteItem.getCrmId();
            Orgnization orgnization = new Orgnization();
            orgnization.setId(crmId);
            Orgnization ol = orgnizationService.queryById(orgnization);
            if (ol == null) {
                throw new ServiceException("ACCT-036",crmId.toString());
            }
            Mvg mvgParam = new Mvg();
            Long id = keyGenerateService.keyGenerate();
            mvgParam.setId(id);
            mvgParam.setMvgParentId(contactId);
            mvgParam.setMvgSubsetId(ol.getId());
            contactOrgMvgMapper.insert(mvgParam);
        }
    }


    /**
     * @author huanglongjian
     * @param contactId
     * @return List
     *
     * @ 获取联系人对应的组织信息
     */
    private List<Orgnization> getContactOrg(Long contactId) throws Exception {
        Orgnization orgQuery = new Orgnization();
        orgQuery.setContactId(contactId);
        return orgnizationService.queryOrgByContactId(orgQuery);
    }

    /**
     * @author huanglongjian
     * @return List
     *
     * @ 获取联系人对应的组织信息
     */
    private List<Orgnization> getAccountOrg(Long accountId) throws Exception {
        Orgnization orgQuery = new Orgnization();
        orgQuery.setAcctId(accountId);
        return orgnizationService.queryOrgByAccountId(orgQuery);
    }

    /**
     * @author huanglongjian
     * @param list
     * @return Long
     * @throws Exception
     *
     * @ 传入主要职位
     */
    private Long getPrimaryOrgId(List<Orgnization> list) throws Exception {
        Long crmId = null;
        for (Orgnization org : list) {
            if ("Y".equals(org.getIsAcctDefault())) {
                crmId = org.getCrmId();
                if (crmId == null) {
                    throw new ServiceException("ACCT-033");
                }
                break;
            }
        }
        if (crmId == null) {
            throw new ServiceException("ACCT-034");
        }
        return crmId;
    }

    /**
     * @author huanglongjian
     * @param list
     * @param isNew
     * @throws Exception
     *
     * @ 设置经销商组织
     */
    private void setAccountOrg(Long accountId, List<Orgnization> list, boolean isNew) throws Exception {
        // 两边数据对比，将没匹配上的数据删除
        List<Orgnization> origList = getAccountOrg(accountId);
        Iterator<Orgnization> it = origList.iterator();
        while (it.hasNext()) {
            Orgnization origItem = it.next();
            boolean existFlag = false;
            for (Orgnization remoteItem : list) {
                if (origItem.getId() != null && origItem.getId().equals(remoteItem.getId())) {
                    existFlag = true;
                    break;
                }
            }
            if (!existFlag) {
                Mvg mvgParam = new Mvg();
                mvgParam.setMvgParentId(accountId);
                mvgParam.setMvgSubsetId(origItem.getId());
                accntOrgMvgMapper.deleteById(mvgParam);
                it.remove();
            }
        }

        for (Orgnization remoteItem : list) {
            boolean existFlag = false;
            for (Orgnization origItem : origList) {
                if (origItem.getId() != null && origItem.getId().equals(remoteItem.getId())) {
                    existFlag = true;
                    break;
                }
            }
            if (existFlag) {
                continue;
            }
            Long crmId = remoteItem.getCrmId();
            Orgnization orgnization = new Orgnization();
            orgnization.setId(crmId);
            Orgnization ol = orgnizationService.queryById(orgnization);
            if (ol == null) {
                throw new ServiceException("ACCT-036",crmId.toString());
            }
            Mvg mvgParam = new Mvg();
            Long id = keyGenerateService.keyGenerate();
            mvgParam.setId(id);
            mvgParam.setMvgParentId(accountId);
            mvgParam.setMvgSubsetId(ol.getId());
            accntOrgMvgMapper.insert(mvgParam);
        }
    }

    /**
     * @author huanglongjian
     * @param accountId
     * @param listAccount
     * @throws Exception
     *
     * @ 设置经销商的资金账户
     */
    private void setDealerAccount(Long accountId, List<DealerAccount> listAccount) throws Exception {
        //1、先查询出当前客户下面的所有的资金账户
        DealerAccount dealerAccountQuery = new DealerAccount();
        dealerAccountQuery.setAccntId(accountId);
        List<DealerAccount> dealerAccountList = dealerAccountService.queryByAccountId(dealerAccountQuery);

        //2、删除当前没有传入的
        for (DealerAccount dealerAccount : dealerAccountList) {
            boolean isExistsFlag = false;
            for (DealerAccount dealerAccountNew : listAccount) {
                if (dealerAccountNew.getIntergrationId().equals(dealerAccount.getIntergrationId())) {
                    isExistsFlag = true;
                }
                dealerAccountNew.setId(dealerAccount.getId());
            }
            if (!isExistsFlag) {
                dealerAccountService.deleteById(dealerAccount);
            }
        }
        for (DealerAccount dealerAccountNew : listAccount) {
            boolean isExistsFlag = false;
            for (DealerAccount dealerAccount : dealerAccountList) {
                if (dealerAccountNew.getIntergrationId().equals(dealerAccount.getIntergrationId())) {
                    isExistsFlag = true;
                }
            }
            if (isExistsFlag) {
                dealerAccountNew.setAccntId(accountId);
                dealerAccountService.update(dealerAccountNew);
            } else {
                Long id = keyGenerateService.keyGenerate();
                dealerAccountNew.setId(id);
                dealerAccountNew.setAccntId(accountId);
                dealerAccountService.insert(dealerAccountNew);
            }
        }
    }

    /**
     * @author huanglongjian
     * @param accountId
     * @return List
     * @throws Exception
     *
     * @ 查询经销商资金账户
     */
    private List<DealerAccount> getDealerAccount(Long accountId) throws Exception {
        DealerAccount dealerAccount = new DealerAccount();
        dealerAccount.setAccntId(accountId);
        return dealerAccountService.queryByAccountId(dealerAccount);
    }

    /**
     * @author huanglongjian
     * @return String
     * @throws Exception
     *
     * @ 获取主要的销售区域Id
     */
    private Long getPrimaryRegionId(List<SaleRegion> saleRegionList) throws Exception {
        SaleRegion sr = null;
        if (saleRegionList != null && saleRegionList.size() > 0) {
            String regionCode = saleRegionList.get(0).getRegionCode();
            sr = saleRegionService.queryByCode(regionCode);
            if (sr == null) {
                throw new ServiceException("ACCT-028",regionCode);
            }
            return sr.getId();
        }
        return null;
    }
}
